package com.zgc.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
@Component
@Slf4j
public class GaodeUtils {
    @Value("${gaode.key}")
    private String key;

    @Value("${gaode.origin}")
    private String origin;
    //调用接口，远程调用时候使用
    @Autowired
    private RestTemplate restTemplate;

    //根据 用户和商家坐标，获取时间和距离
    public Map<String,String> getDistanceAndTime(String yhzb){
       JSONObject jsonObject= restTemplate.getForObject("https://restapi.amap.com/v5/direction/walking?key="+key+"&origin="+origin+"&destination="+yhzb, JSONObject.class);
        JSONObject jb= jsonObject.getJSONObject("route").getJSONArray("paths").getJSONObject(0);
        BigDecimal distance= jb.getBigDecimal("distance");//返回距离
        distance=distance.divide(new BigDecimal(1000),2,BigDecimal.ROUND_HALF_UP);
        int duration= jb.getJSONObject("cost").getIntValue("duration");
        Map<String,String> map=new HashMap<>();
        log.info("distance==="+distance+"===="+duration/60+10+"");
        map.put("distance",distance+"");
        map.put("duration",duration/60+10+""); //时间是秒为单位，加上10分钟就是预计送达时长
        return map;
    }
}

